import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

export const useUserStore = defineStore('user', () => {
  const accountId = ref('')
  const username = ref('')
  const token = ref('')

  function setUserInfo(id: string, name: string, userToken: string) {
    accountId.value = id
    username.value = name
    token.value = userToken
    // 同时存入本地存储，以便页面刷新后保持登录状态
    localStorage.setItem('accountId', id)
    localStorage.setItem('username', name)
    localStorage.setItem('token', userToken)
  }

  function loadUserInfo() {
    accountId.value = localStorage.getItem('accountId') || ''
    username.value = localStorage.getItem('username') || ''
    token.value = localStorage.getItem('token') || ''
  }

  function clearUserInfo() {
    accountId.value = ''
    username.value = ''
    token.value = ''
    localStorage.removeItem('accountId')
    localStorage.removeItem('username')
    localStorage.removeItem('token')
  }

  return { accountId, username, token, setUserInfo, loadUserInfo, clearUserInfo }
})
